﻿using System;
using System.Diagnostics;
using Service4u2.Common;

#if SILVERLIGHT
using System.Windows;
#endif

namespace Service4u2.Json
{
    
    /// <summary>
    /// A base class for Json related services.
    /// </summary>
    /// <typeparam name="TResultType">The type of the result.</typeparam>
    public abstract class BaseJsonService<TResultType> : BaseDataService<TResultType>
    {
        
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseJsonService&lt;TResultType&gt;"/> class.
        /// </summary>
        public BaseJsonService()
        {
            
        }
        
        /// <summary>
        /// Handles the client result string.
        /// </summary>
        /// <param name="downloadedString">The downloaded string.</param>
        protected override void HandleResultString(string downloadedString)
        {
            // Check for html doctype and report error if found.
            int takeLength = downloadedString.Length > 20 ? 20 : downloadedString.Length;
            if (downloadedString.Substring(0, takeLength).Contains("!DOCTYPE html"))
            {
                HandleError(new NotSupportedException("The service call returned html and not json"));
                return;
            }

            Debug.WriteLine("Service4u2: JSON Response: \r\n{0}", downloadedString);
            var result = JsonHelper.Deserialize<TResultType>(downloadedString);

#if SILVERLIGHT
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                    OnGotResult(result));
#else
                OnGotResult(result);
#endif

        }
    }
}
